#encoding=utf8

# 导入相关的模块
import theano
from theano import tensor as T
from theano.tensor.nnet import conv
import numpy
import pylab
from PIL import Image


# 产生随机数的种子
rng = numpy.random.RandomState(23455)

# convolution layer的输入，根据theano，它应该是一个4d tensor
input = T.tensor4(name='input')
# 共享权值W，它的shape为2,3,9,9
w_shp = (2,3,9,9)
w_bound = numpy.sqrt(3*9*9)
W = theano.shared(numpy.asarray(rng.uniform(low= -1.0/w_bound, high = 1.0/w_bound,size=w_shp),dtype=input.dtype),name='W')
# 利用卷积核W对input进行卷积运算
conv_out = conv.conv2d(input,W)
# 偏执向量b
b_shp = (2,)
b = theano.shared(numpy.asarray(rng.uniform(low= -.5, high = .5,size=b_shp),dtype=input.dtype),name='b')
# 计算sigmoid函数
output = T.nnet.sigmoid(conv_out+b.dimshuffle('x',0,'x','x'))
# 输入输出function
f = theano.function([input],output)

if __name__ == "__main__":
    # 读入图像
    img = Image.open("../dataset/images/img_studio.JPG", mode='r')
    # 将输入图像存入在array中
    img = numpy.array(img,dtype='float64')/256
    print img.shape
    print img
    # 对输入图像进行reshape
    img_=img.transpose(2,0,1).reshape(1,3,2448,3264)
    # 利用convolution kernel对输入图像进行卷积运算
    print img_.shape
    print img_
    filtered_img=f(img_)


    # 显示原始图像
    pylab.subplot(1,3,1);pylab.axis('off');pylab.imshow(img);pylab.gray()
    # 显示filter后的图像的channel1
    pylab.subplot(1,3,2);pylab.axis('off');pylab.imshow(filtered_img[0,0,:,:])
    # 显示filter后的图像的channel2
    pylab.subplot(1,3,3);pylab.axis('off');pylab.imshow(filtered_img[0,1,:,:])
    # 显示
    pylab.show()